package cn.sskxyz.security.authorization.service;

import cn.sskxyz.mybatis.mode.Page;
import cn.sskxyz.security.authorization.dao.AuthorizationDao;
import cn.sskxyz.security.authorization.dao.UserDao;
import cn.sskxyz.security.authorization.model.Resource;
import cn.sskxyz.security.authorization.model.Role;
import cn.sskxyz.security.core.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.AntPathMatcher;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class UserService implements UserDetailsService {
    @Autowired
    private UserDao userDao;

    @Autowired
    private AuthorizationDao authorizationDao;

    @Autowired
    private PasswordEncoder passwordEncoder;

    private AntPathMatcher matcher = new AntPathMatcher();

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userDao.selectUserByUsername(username);
        List<Role> roles = authorizationDao.selectUserRolesByUserId(user.getId());
        List<SimpleGrantedAuthority> authorities = roles.stream()
                .map(role -> new SimpleGrantedAuthority(role.getName()))
                .collect(Collectors.toList());
        user.setAuthorities(authorities);
        return user;
    }

    public void addUser(User user) {
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        userDao.insertSingleUser(user);
    }

    public Page<List<User>> queryUserList(int currentPage, int pageSize) {
        Page<List<User>> page = new Page<>(currentPage, pageSize);
        List<User> userList = userDao.selectUserList(page);
        page.setData(userList);
        return page;
    }

    @Cacheable(value = "basic", keyGenerator = "cacheKeyGenerator")
    public boolean checkPermission(String module, String uri, Long userId) {
        List<Resource> resources = queryUserPermission(module, userId);
        if (resources == null || resources.size() == 0) {
            return false;
        }

        Resource resource = resources.stream().filter(res -> matcher.match(res.getResource(), uri))
                .findFirst().orElse(null);
        if (resource == null) {
            return false;
        }
        return true;
    }

    @Cacheable(keyGenerator = "cacheKeyGenerator")
    public List<Resource> queryUserPermission(String module, Long userId) {
        return authorizationDao.selectUserPermissionByUserIdWithModule(userId, module);
    }
}
